<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTextStyle: '#0000FF',
    navigationBarTitleText: '人事档案修改',
    navigationStyle: 'custom',
    navigationBarBackgroundColor: '#a8dced',
  },
}
</route>

<template>
  <view class="container">
    <wd-form ref="form" :model="model">
      <wd-cell-group border>
        <view class="flexBox">
          <view class="w-[110px] left-label">头像</view>
          <wd-upload
            v-model:file-list="fileList"
            image-mode="aspectFill"
            :limit="1"
            :action="action"
          ></wd-upload>
        </view>
        <wd-input
          label="工号"
          prop="userName"
          disabled
          v-model="model.userName"
          placeholder="请输入工号"
          :rules="[{ required: true, message: '请填写工号' }]"
        />
        <wd-input
          label="姓名"
          prop="nickName"
          v-model="model.nickName"
          placeholder="请输入姓名"
          :rules="[{ required: true, message: '请填写姓名' }]"
        />
        <wd-select-picker
          label="性别"
          v-model="model.sex"
          :columns="sexList"
          type="radio"
          placeholder="请选择性别"
        ></wd-select-picker>
        <wd-select-picker
          label="基地"
          readonly
          v-model="model.workPlace"
          @confirm="changeBase"
          :columns="baseList"
          type="radio"
          placeholder="请选择基地"
        ></wd-select-picker>
        <wd-select-picker
          label="厂区"
          readonly
          v-model="model.plantCode"
          :columns="factoryList"
          type="radio"
          placeholder="请选择厂区"
        ></wd-select-picker>
        <wd-input
          label="部门"
          suffix-icon="arrow-right"
          readonly
          v-model="model.deptName"
          placeholder="请选择部门"
          @click="showTreePicker"
        />
        <wd-picker readonly :columns="postOptions" label="岗位" v-model="model.postId" />
        <wd-input
          label="手机号"
          prop="phonenumber"
          v-model="model.phonenumber"
          placeholder="请输入手机号"
        />
        <wd-input
          label="身份证号"
          prop="idCard"
          v-model="model.idCard"
          placeholder="请输入身份证号"
        />
        <wd-datetime-picker
          v-model="model.hireDate"
          :default-value="defaultValue"
          label="入职日期"
          type="date"
        />
        <wd-datetime-picker
          v-model="model.birthDate"
          :default-value="defaultValue"
          label="出生日期"
          type="date"
        />
        <wd-picker
          :columns="politicalOutlookList"
          label="政治面貌"
          v-model="model.politicalOutlook"
        />
        <wd-picker :columns="maritalStatusList" label="婚姻状况" v-model="model.maritalStatus" />
        <wd-col-picker
          label="籍贯"
          v-model="model.nativePlaceList"
          :columns="companyList"
          :placeholder="model.nativePlaceName"
          :column-change="columnChange"
          label-key="label"
          value-key="value"
        ></wd-col-picker>
        <wd-col-picker
          label="户籍地址"
          v-model="model.residenceList"
          :columns="companyList"
          :placeholder="model.householdRegistrationAddressName"
          :column-change="columnChange2"
          label-key="label"
          value-key="value"
        ></wd-col-picker>
        <wd-select-picker
          label="户籍类型"
          v-model="model.householdRegistrationType"
          :columns="householdRegistrationTypeList"
          type="radio"
          placeholder="请选择户籍类型"
        ></wd-select-picker>
        <view class="flexBox border-t">
          <view class="w-[130px] left-label">退伍军人</view>
          <wd-radio-group shape="dot" inline v-model="model.veteran">
            <wd-radio :value="1">是</wd-radio>
            <wd-radio :value="2">否</wd-radio>
          </wd-radio-group>
        </view>
        <view class="flexBox border-t">
          <view class="w-[130px] left-label">建档贫困户</view>
          <wd-radio-group shape="dot" inline v-model="model.familiesInNeed">
            <wd-radio :value="1">是</wd-radio>
            <wd-radio :value="2">否</wd-radio>
          </wd-radio-group>
        </view>
        <wd-input
          label="现居地址"
          prop="currentResidentialAddress"
          v-model="model.currentResidentialAddress"
          placeholder="请输入现居地址"
        />
        <wd-input
          label="紧急联系人"
          prop="emergencyContact"
          v-model="model.emergencyContact"
          placeholder="请输入紧急联系人"
        />
        <wd-select-picker
          label="紧急联系人关系"
          v-model="model.emergencyRelationship"
          :columns="emergencyRelationshipList"
          type="radio"
          placeholder="请选择紧急联系人关系"
        ></wd-select-picker>
        <wd-input
          label="紧急联系人电话"
          prop="emergencyContactPhone"
          v-model="model.emergencyContactPhone"
          placeholder="请输入紧急联系人电话"
        />
        <!-- <wd-datetime-picker
          v-model="model.separationTime"
          :default-value="defaultValue"
          label="离职日期"
          type="date"
        /> -->
        <wd-input
          label="开户银行"
          prop="payrollCardOpeningBank"
          v-model="model.payrollCardOpeningBank"
          placeholder="请输入开户银行"
        />
        <wd-input
          label="银行账号"
          prop="payrollCardClosingBank"
          v-model="model.payrollCardClosingBank"
          placeholder="请输入银行账号"
        />
        <wd-textarea label="备注" v-model="model.remark" placeholder="请填写备注" />
      </wd-cell-group>
    </wd-form>
    <ba-tree-picker
      ref="treePicker"
      :multiple="false"
      @select-change="changeDept"
      title="归属部门"
      :localdata="enabledDeptOptions"
      valueKey="id"
      textKey="label"
      childrenKey="children"
    />
    <wd-collapse v-model="collapseValue">
      <wd-collapse-item name="1">
        <template #title>
          <view class="header">
            <text style="color: red">学历信息</text>
            <view @click.stop="">
              <wd-button size="small" @click="(schoolShow = true), (schoolModel = {})">
                新增
              </wd-button>
            </view>
          </view>
        </template>
        <wd-card v-for="(item, index) in userSchoolList" :key="item.id">
          <template #title>
            <view class="header mb-[20px]">
              <view class="text-[14px] font-bold">学历信息{{ index + 1 }}</view>
              <view class="title">
                <view class="mr-[10px]">
                  <wd-button size="small" @click="(schoolShow = true), (schoolModel = item)">
                    编辑
                  </wd-button>
                </view>
                <wd-button size="small" type="warning" @click="() => delSchool(item)">
                  删除
                </wd-button>
              </view>
            </view>
            <view class="infoItem">
              <view class="item-title">学校名称</view>
              <view>{{ item.schoolName }}</view>
            </view>
            <view class="infoItem">
              <view class="item-title">入学时间</view>
              <view>{{ item.startTime }}</view>
            </view>
            <view class="infoItem">
              <view class="item-title">毕业时间</view>
              <view>{{ item.endTime }}</view>
            </view>
            <view class="infoItem">
              <view class="item-title">学历类型</view>
              <view>{{ item.graduationSchoolType == 1 ? '全日制' : '非全日制' }}</view>
            </view>
            <view class="infoItem">
              <view class="item-title">学历</view>
              <view>
                {{
                  educationTypeDict.filter((item1) => item1.value == item.degree)[0]
                    ? educationTypeDict.filter((item1) => item1.value == item.degree)[0].label
                    : ''
                }}
              </view>
            </view>
            <view class="infoItem">
              <view class="item-title">专业</view>
              <view>{{ item.major }}</view>
            </view>
          </template>
        </wd-card>
      </wd-collapse-item>
      <wd-collapse-item name="2">
        <template #title>
          <view class="header">
            <text style="color: red">工作经历</text>
            <view @click.stop="">
              <wd-button size="small" @click="(workShow = true), (workModel = {})">新增</wd-button>
            </view>
          </view>
        </template>
        <wd-card v-for="(item, index) in workList" :key="item.id">
          <template #title>
            <view class="header mb-[20px]">
              <view class="text-[14px] font-bold">工作经历{{ index + 1 }}</view>
              <view class="title">
                <view class="mr-[10px]">
                  <wd-button size="small" @click="(workShow = true), (workModel = item)">
                    编辑
                  </wd-button>
                </view>
                <wd-button size="small" type="warning" @click="() => delWork(item)">删除</wd-button>
              </view>
            </view>
            <view class="infoItem">
              <view class="item-title">任职公司</view>
              <view>{{ item.employedCompany }}</view>
            </view>
            <view class="infoItem">
              <view class="item-title">入职时间</view>
              <view>{{ item.startTime }}</view>
            </view>
            <view class="infoItem">
              <view class="item-title">离职时间</view>
              <view>{{ item.endTime }}</view>
            </view>
            <view class="infoItem">
              <view class="item-title">部门及岗位</view>
              <view>{{ item.departmentsPositions }}</view>
            </view>
            <view class="infoItem">
              <view class="item-title">证明人及联系方式</view>
              <view>{{ item.witnessAndPhone }}</view>
            </view>
          </template>
        </wd-card>
      </wd-collapse-item>
      <wd-collapse-item name="3">
        <template #title>
          <view class="header">
            <text style="color: red">人员证书</text>
            <view @click.stop="">
              <wd-button size="small" @click="(certificateShow = true), (certificateModel = {})">
                新增
              </wd-button>
            </view>
          </view>
        </template>
        <wd-card v-for="(item, index) in certificateList" :key="item.id">
          <template #title>
            <view class="header mb-[20px]">
              <view class="text-[14px] font-bold">人员证书{{ index + 1 }}</view>
              <view class="title">
                <view class="mr-[10px]">
                  <wd-button
                    size="small"
                    @click="
                      (certificateShow = true),
                        (certificateModel = {
                          ...item,
                          certificateType: item.certificateType + '',
                          fileList: item.certificateFile
                            ? [{ url: item.certificateFile, response: item.certificateFile }]
                            : [],
                        })
                    "
                  >
                    编辑
                  </wd-button>
                </view>
                <wd-button size="small" type="warning" @click="() => delCertificate(item)">
                  删除
                </wd-button>
              </view>
            </view>
            <view class="infoItem">
              <view class="item-title">证书名称</view>
              <view>{{ item.certificateName }}</view>
            </view>
            <view class="infoItem">
              <view class="item-title">发证日期</view>
              <view>{{ item.startTime }}</view>
            </view>
            <view class="infoItem">
              <view class="item-title">到期日期</view>
              <view>{{ item.endTime }}</view>
            </view>
            <view class="infoItem">
              <view class="item-title">证书类型</view>
              <view>
                {{
                  certificateTypeDict.filter((item1) => item1.value == item.certificateType)[0]
                    ? certificateTypeDict.filter((item1) => item1.value == item.certificateType)[0]
                        .label
                    : ''
                }}
              </view>
            </view>
            <view class="infoItem">
              <view class="item-title">编号</view>
              <view>{{ item.certificateNo }}</view>
            </view>
            <view class="infoItem">
              <view class="item-title">证书文件</view>
              <view>
                请前往电脑客户端查看
                <!-- <view v-if="item.certificateFile">
                  <wd-button
                    type="icon"
                    icon="download"
                    @click="() => downloadCertificate(item.certificateFile)"
                  ></wd-button>
                </view>
                <view v-else>无</view> -->
              </view>
            </view>
            <view class="infoItem">
              <view class="item-title">是否有效</view>
              <view>
                {{
                  item.certificateStatus == 1 ? '有效' : item.certificateStatus == 2 ? '无效' : ''
                }}
              </view>
            </view>
            <!-- <view class="infoItem">
              <view class="item-title">证书文件</view>
              <view>
                <view v-if="item.certificateFile">
                  <wd-button
                    size="small"
                    icon="download1"
                    @click="() => downloadFile(item.certificateFile)"
                  >
                    下载
                  </wd-button>
                </view>
                <view v-else>无</view>
              </view>
            </view> -->
          </template>
        </wd-card>
      </wd-collapse-item>
      <wd-collapse-item name="4" v-if="showCode">
        <template #title>
          <view class="header">
            <text style="color: red">合同信息</text>
            <view @click.stop="">
              <wd-button size="small" @click="(contractShow = true), (contractModel = {})">
                新增
              </wd-button>
            </view>
          </view>
        </template>
        <wd-card v-for="(item, index) in contractList" :key="item.id">
          <template #title>
            <view class="header mb-[20px]">
              <view class="text-[14px] font-bold">合同信息{{ index + 1 }}</view>
              <view class="title">
                <view class="mr-[10px]">
                  <wd-button
                    size="small"
                    @click="
                      (contractShow = true),
                        (contractModel = {
                          ...item,
                        })
                    "
                  >
                    编辑
                  </wd-button>
                </view>
                <wd-button size="small" type="warning" @click="() => delContract(item)">
                  删除
                </wd-button>
              </view>
            </view>
            <view class="infoItem">
              <view class="item-title">合同公司</view>
              <view>{{ item.contractsCompany }}</view>
            </view>
            <view class="infoItem">
              <view class="item-title">开始日期</view>
              <view>{{ item.startTime }}</view>
            </view>
            <view class="infoItem">
              <view class="item-title">结束日期</view>
              <view>{{ item.endTime }}</view>
            </view>
            <view class="infoItem">
              <view class="item-title">合同类型</view>
              <view>
                {{
                  contractTypeDict.filter((item1) => item1.value == item.contractsType)[0]
                    ? contractTypeDict.filter((item1) => item1.value == item.contractsType)[0].label
                    : ''
                }}
              </view>
            </view>
            <view class="infoItem">
              <view class="item-title">合同期限</view>
              <view>{{ item.contractsTerm }}</view>
            </view>
            <view class="infoItem">
              <view class="item-title">签订次数</view>
              <view>{{ item.contractsCount }}</view>
            </view>
            <view class="infoItem">
              <view class="item-title">证书文件</view>
              <view>
                请前往电脑客户端查看
                <!-- <view v-if="item.certificateFile">
                  <wd-button
                    type="icon"
                    icon="download"
                    @click="() => downloadCertificate(item.certificateFile)"
                  ></wd-button>
                </view>
                <view v-else>无</view> -->
              </view>
            </view>
          </template>
        </wd-card>
      </wd-collapse-item>
      <wd-collapse-item name="5">
        <template #title>
          <view class="header">
            <text style="color: red">家庭关系</text>
            <view @click.stop="">
              <wd-button size="small" @click="(familyShow = true), (familyModel = {})">
                新增
              </wd-button>
            </view>
          </view>
        </template>
        <wd-card v-for="(item, index) in familyList" :key="item.id">
          <template #title>
            <view class="header mb-[20px]">
              <view class="text-[14px] font-bold">家庭关系{{ index + 1 }}</view>
              <view class="title">
                <view class="mr-[10px]">
                  <wd-button
                    size="small"
                    @click="(familyShow = true), (familyModel = { ...item, sex: item.sex + '' })"
                  >
                    编辑
                  </wd-button>
                </view>
                <wd-button size="small" type="warning" @click="() => delFamily(item)">
                  删除
                </wd-button>
              </view>
            </view>
            <view class="infoItem">
              <view class="item-title">姓名</view>
              <view>{{ item.nickName }}</view>
            </view>
            <view class="infoItem">
              <view class="item-title">关系</view>
              <view>
                {{
                  familyRelationshipDict.filter((item1) => item1.value == item.relationship)[0]
                    ? familyRelationshipDict.filter((item1) => item1.value == item.relationship)[0]
                        .label
                    : ''
                }}
              </view>
            </view>
            <view class="infoItem">
              <view class="item-title">性别</view>
              <view>
                {{
                  sexList.filter((item1) => item1.value == item.sex)[0]
                    ? sexList.filter((item1) => item1.value == item.sex)[0].label
                    : ''
                }}
              </view>
            </view>
            <view class="infoItem">
              <view class="item-title">出生日期</view>
              <view>{{ item.birthDate }}</view>
            </view>
            <view class="infoItem">
              <view class="item-title">工作单位</view>
              <view>{{ item.employedCompany }}</view>
            </view>
            <view class="infoItem">
              <view class="item-title">联系电话</view>
              <view>{{ item.phonenumber }}</view>
            </view>
          </template>
        </wd-card>
      </wd-collapse-item>
    </wd-collapse>
    <view class="bottom-btn">
      <wd-button type="primary" size="large" custom-class="btn" @click="submit">保存</wd-button>
    </view>
    <!-- 学历信息 -->
    <view class="oppbox">
      <wd-popup
        v-model="schoolShow"
        closable
        custom-style="border-radius:32rpx; width: 90%;min-height:80vh"
      >
        <view class="popTitle">{{ schoolModel.id ? '修改学历' : '新增学历' }}</view>
        <view class="py-[10px] pt-[40px] px-[15px] contentBox">
          <wd-form :model="schoolModel" ref="schoolForm">
            <wd-input
              label="学校名称"
              prop="schoolName"
              v-model="schoolModel.schoolName"
              placeholder="请输入学校名称"
              :rules="[{ required: true, message: '请填写学校名称' }]"
            />
            <wd-datetime-picker
              v-model="schoolModel.startTime"
              :default-value="defaultValue"
              label="入学时间"
              type="date"
              prop="startTime"
              :rules="[{ required: true, message: '请选择入学时间' }]"
            />
            <wd-datetime-picker
              v-model="schoolModel.endTime"
              :default-value="defaultValue"
              label="毕业时间"
              type="date"
              prop="endTime"
              :rules="[{ required: true, message: '请选择毕业时间' }]"
            />
            <wd-select-picker
              label="学历类型"
              v-model="schoolModel.graduationSchoolType"
              :columns="graduationSchoolTypeList"
              type="radio"
              placeholder="请选择学历类型"
              prop="graduationSchoolType"
              :rules="[{ required: true, message: '请选择学历类型' }]"
            ></wd-select-picker>
            <wd-select-picker
              label="学历"
              v-model="schoolModel.degree"
              :columns="educationTypeDict"
              type="radio"
              placeholder="请选择学历"
              prop="degree"
              :rules="[{ required: true, message: '请选择学历' }]"
            ></wd-select-picker>
            <wd-input
              label="专业"
              prop="major"
              v-model="schoolModel.major"
              placeholder="请输入专业"
              :rules="[{ required: true, message: '请填写专业' }]"
            />
            <view class="footer mt-[20px] flex justify-end">
              <wd-button type="primary" size="small" @click="shoolSubmit">提交</wd-button>
            </view>
          </wd-form>
        </view>
      </wd-popup>
    </view>
    <!-- 工作经历信息 -->
    <view class="oppbox">
      <wd-popup
        v-model="workShow"
        closable
        custom-style="border-radius:32rpx; width: 90%;min-height:80vh"
      >
        <view class="popTitle">{{ workModel.id ? '修改工作经历' : '新增工作经历' }}</view>
        <view class="py-[10px] pt-[40px] px-[15px] contentBox">
          <wd-form :model="workModel" ref="workForm">
            <wd-input
              label="任职公司"
              prop="employedCompany"
              v-model="workModel.employedCompany"
              placeholder="请输入任职公司"
              :rules="[{ required: true, message: '请填写任职公司' }]"
            />
            <wd-datetime-picker
              v-model="workModel.startTime"
              :default-value="defaultValue"
              label="入职时间"
              type="date"
              prop="startTime"
              :rules="[{ required: true, message: '请选择入职时间' }]"
            />
            <wd-datetime-picker
              v-model="workModel.endTime"
              :default-value="defaultValue"
              label="离职时间"
              type="date"
              prop="endTime"
              :rules="[{ required: true, message: '请选择离职时间' }]"
            />
            <wd-input
              label="部门及岗位"
              prop="departmentsPositions"
              v-model="workModel.departmentsPositions"
              placeholder="请输入部门及岗位"
              :rules="[{ required: true, message: '请填写部门及岗位' }]"
            />
            <wd-input
              label="证明人及联系方式"
              prop="witnessAndPhone"
              v-model="workModel.witnessAndPhone"
              placeholder="请输入证明人及联系方式"
              :rules="[{ required: true, message: '请填写证明人及联系方式' }]"
            />
            <view class="footer mt-[20px] flex justify-end">
              <wd-button type="primary" size="small" @click="workSubmit">提交</wd-button>
            </view>
          </wd-form>
        </view>
      </wd-popup>
    </view>
    <!-- 人员证书信息 -->
    <view class="oppbox">
      <wd-popup
        v-model="certificateShow"
        closable
        custom-style="border-radius:32rpx; width: 90%;min-height:80vh"
      >
        <view class="popTitle">{{ certificateModel.id ? '修改人员证书' : '新增人员证书' }}</view>
        <view class="py-[10px] pt-[40px] px-[15px] contentBox">
          <wd-form :model="certificateModel" ref="certificateForm">
            <wd-input
              label="证书名称"
              prop="certificateName"
              v-model="certificateModel.certificateName"
              placeholder="请输入证书名称"
              :rules="[{ required: true, message: '请填写证书名称' }]"
            />
            <wd-input
              label="证书编号"
              prop="certificateNo"
              v-model="certificateModel.certificateNo"
              placeholder="请输入证书编号"
              :rules="[{ required: true, message: '请填写证书编号' }]"
            />
            <wd-select-picker
              label="证书类型"
              v-model="certificateModel.certificateType"
              :columns="certificateTypeDict"
              type="radio"
              placeholder="请选择证书类型"
              prop="certificateType"
              :rules="[{ required: true, message: '请选择证书类型' }]"
            ></wd-select-picker>
            <wd-datetime-picker
              v-model="certificateModel.startTime"
              :default-value="defaultValue"
              label="发证日期"
              type="date"
              prop="startTime"
              :rules="[{ required: true, message: '请选择发证日期' }]"
            />
            <wd-datetime-picker
              v-model="certificateModel.endTime"
              :default-value="defaultValue"
              label="到期日期"
              type="date"
              prop="endTime"
              :rules="[{ required: true, message: '请选择到期日期' }]"
            />
            <!-- <view class="flexBox">
              <view class="w-[110px] left-label">证书文件</view>
              <wd-upload
                v-model:file-list="certificateModel.fileList"
                image-mode="aspectFill"
                :limit="1"
                reupload
                :action="action"
              ></wd-upload>
            </view> -->
            <view class="footer mt-[20px] flex justify-end">
              <view class="mr-[10px]">
                <wd-button type="primary" size="small" @click="certificateSubmit">提交</wd-button>
              </view>
              <wd-button type="info" size="small" @click="certificateShow = false">取消</wd-button>
            </view>
          </wd-form>
        </view>
      </wd-popup>
    </view>
    <!-- 家庭信息 -->
    <view class="oppbox">
      <wd-popup
        v-model="familyShow"
        closable
        custom-style="border-radius:32rpx; width: 90%;min-height:80vh"
      >
        <view class="popTitle">{{ familyModel.id ? '修改家庭信息' : '新增家庭信息' }}</view>
        <view class="py-[10px] pt-[40px] px-[15px] contentBox">
          <wd-form :model="familyModel" ref="familyForm">
            <wd-input
              label="姓名"
              prop="nickName"
              v-model="familyModel.nickName"
              placeholder="请输入姓名"
              :rules="[{ required: true, message: '请填写姓名' }]"
            />
            <wd-select-picker
              label="关系"
              v-model="familyModel.relationship"
              :columns="familyRelationshipDict"
              type="radio"
              placeholder="请选择关系"
              prop="relationship"
              :rules="[{ required: true, message: '请选择关系' }]"
            ></wd-select-picker>
            <wd-select-picker
              label="性别"
              v-model="familyModel.sex"
              :columns="sexList"
              type="radio"
              placeholder="请选择性别"
              prop="sex"
              :rules="[{ required: true, message: '请选择性别' }]"
            ></wd-select-picker>
            <wd-input
              label="手机号"
              prop="phonenumber"
              v-model="familyModel.phonenumber"
              placeholder="请输入手机号"
              :rules="[{ required: true, message: '请填写手机号' }]"
            />
            <wd-datetime-picker
              v-model="familyModel.birthDate"
              :default-value="defaultValue"
              label="生日"
              type="date"
              prop="birthDate"
              :rules="[{ required: true, message: '请选择生日' }]"
            />
            <wd-input
              label="工作单位"
              prop="employedCompany"
              v-model="familyModel.employedCompany"
              placeholder="请输入工作单位"
              :rules="[{ required: true, message: '请填写工作单位' }]"
            />
            <view class="footer mt-[20px] flex justify-end">
              <view class="mr-[10px]">
                <wd-button type="primary" size="small" @click="familySubmit">提交</wd-button>
              </view>
              <wd-button type="info" size="small" @click="familyShow = false">取消</wd-button>
            </view>
          </wd-form>
        </view>
      </wd-popup>
    </view>
  </view>
</template>

<script lang="js" setup>
import { onLoad, onReachBottom } from '@dcloudio/uni-app'
import { useSysStore } from '@/store/systemInfo'
import {
  getUserInfoDetail,
  getBaseData,
  getFactoryData,
  getDeptTree,
  getPostData,
  getCityDict,
  updateSchoolInfo,
  addSchoolInfo,
  deleteSchoolInfo,
  updateWorkInfo,
  addWorkInfo,
  deleteWorkInfo,
  updateCertificateInfo,
  addCertificateInfo,
  deleteCertificateInfo,
  updateFamilyInfo,
  addFamilyInfo,
  deleteFamilyInfo,
  updateUserInfo,
} from '@/api/user.js'
import { getDict } from '@/utils/publicFnc.js'
import baTreePicker from '@/components/ba-tree-picker/ba-tree-picker.vue'
import { useColPickerData } from '@/hooks/useColPickerData'
import dayjs from 'dayjs'
import LnChangeFile from '../../../components/ln-change-file/ln-change-file.vue'
import dd from 'dingtalk-jsapi' // 引入钉钉api
defineOptions({
  name: 'BasicInformation',
})

const showCode = ref(false)
const companyList = ref([])
const { colPickerData, findChildrenByCode } = useColPickerData()
const treePicker = ref()
const defaultValue = ref(Date.now())
const sysStore = useSysStore()
const config = ref({
  title: '',
  size: 20000,
  limit: 1,
  headers: {
    Authorization: 'Bearer ' + sysStore.token,
  },
  formData: {},
  automatic: true,
  fileMediatype: 'all',
})
const model = ref({ deptId: null, nativePlaceList: [], residenceList: [] })
const form = ref()
const collapseValue = ref(['1'])
const action = ref(import.meta.env.VITE_UPLOAD_BASEURL)
const fileList = ref([])
const userId = ref()
const sexList = ref([])
const baseList = ref([])
const factoryList = ref([])
const enabledDeptOptions = ref([])
const postOptions = ref([])
const politicalOutlookList = ref([
  {
    value: '党员',
    label: '党员',
  },
  {
    value: '团员',
    label: '团员',
  },
  {
    value: '群众',
    label: '群众',
  },
  {
    value: '其他党派',
    label: '其他党派',
  },
])
const maritalStatusList = ref([
  {
    value: '0',
    label: '未婚',
  },
  {
    value: '1',
    label: '已婚',
  },
  {
    value: '2',
    label: '离异',
  },
])
const householdRegistrationTypeList = ref([])
const emergencyRelationshipList = ref([])
const schoolForm = ref()

// 学历信息
const userSchoolList = ref([])
// 学历字典
const educationTypeDict = ref([])
const schoolShow = ref(false)
const schoolModel = ref({})
// 学历类型
const graduationSchoolTypeList = ref([
  {
    value: '1',
    label: '全日制',
  },
  {
    value: '2',
    label: '非全日制',
  },
])

// 工作经历
const workList = ref([])
const workShow = ref(false)
const workModel = ref({})
const workForm = ref()

// 人员证书
const certificateList = ref([])
const certificateShow = ref(false)
const certificateModel = ref({})
const certificateForm = ref()
// 证书类型字典
const certificateTypeDict = ref([])
const certificateFileList = ref([])

// 合同信息
const contractList = ref([])
const contractShow = ref(false)
const contractModel = ref({})
const contractForm = ref()
// 合同类型字典
const contractTypeDict = ref([])

// 家庭关系
const familyList = ref([])
const familyShow = ref(false)
const familyModel = ref({})
const familyForm = ref()
// 家庭关系字典
const familyRelationshipDict = ref([])

onMounted(async () => {
  getCityDictData()
  userId.value = sysStore.userInfo.userId
  await getDeptTreeData()
  await getUserInfo()
  getBaseList()
  getFactoryList(model.value.workPlace)
  sexList.value = await getDict('sys_user_sex')
  householdRegistrationTypeList.value = await getDict('household_registration_type')
  emergencyRelationshipList.value = await getDict('emergency_relationship')
  educationTypeDict.value = await getDict('user_degree')
  certificateTypeDict.value = await getDict('certificate_type')
  contractTypeDict.value = await getDict('contracts_type')
  familyRelationshipDict.value = await getDict('emergency_relationship')
  // treePicker.value._show()
})

// 点击保存
const submit = async () => {
  form.value.validate().then(async (data) => {
    if (data.valid) {
      const res = await updateUserInfo({
        ...model.value,
        // userId: sysStore.userInfo.userId,
      })
      if (res.data.code == 200) {
        uni.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 2000,
        })
        getUserInfo()
      }
    }
  })
}

// 家庭成员保存
const familySubmit = async () => {
  familyForm.value.validate().then(async (data) => {
    if (data.valid) {
      if (familyModel.value.id) {
        const res = await updateFamilyInfo({
          ...familyModel.value,
          userId: sysStore.userInfo.userId,
          birthDate: dayjs(familyModel.value.birthDate).format('YYYY-MM-DD'),
        })
        if (res.data.code == 200) {
          uni.showToast({
            title: '修改成功',
            icon: 'success',
            duration: 2000,
          })
          familyShow.value = false
          getUserInfo()
        }
      } else {
        const res = await addFamilyInfo({
          ...familyModel.value,
          userId: sysStore.userInfo.userId,
          birthDate: dayjs(familyModel.value.birthDate).format('YYYY-MM-DD'),
        })
        if (res.data.code == 200) {
          uni.showToast({
            title: '新增成功',
            icon: 'success',
            duration: 2000,
          })
          familyShow.value = false
          getUserInfo()
        }
      }
    }
  })
}

// 删除家庭成员
const delFamily = async (item) => {
  uni.showModal({
    title: '提示',
    content: '确定删除吗？',
    confirmText: '确定',
    cancelText: '取消',
    success: async (res) => {
      if (res.confirm) {
        const res = await deleteFamilyInfo(item.id)
        if (res.data.code == 200) {
          uni.showToast({
            title: '删除成功',
            icon: 'success',
            duration: 2000,
          })
          getUserInfo()
        }
      }
    },
  })
}

// 下载人员证书文件
const downloadCertificate = (filePath) => {
  uni.downloadFile({
    url: filePath,
    success: (res) => {
      if (res.statusCode === 200) {
        uni.saveFile({
          tempFilePath: res.tempFilePath,
          success: (res) => {
            uni.showToast({
              title: '下载成功',
              icon: 'success',
              duration: 2000,
            })
          },
        })
      }
    },
  })
}

// 去除字符串中指定重复字符段
const removeDuplicateSubstring = (str, target) => {
  if (!target) return str
  let result = ''
  let i = 0
  let hasFound = false

  while (i < str.length) {
    if (str.slice(i, i + target.length) === target) {
      if (!hasFound) {
        result += target
        hasFound = true
      }
      i += target.length
    } else {
      result += str[i]
      i++
    }
  }
  return result
}

// 证书保存
const certificateSubmit = async () => {
  let url = ''
  if (certificateModel.value.fileList && certificateModel.value.fileList.length > 0) {
    if (
      Object.prototype.toString.call(JSON.parse(certificateModel.value.fileList[0].response)) ===
      '[object Object]'
    ) {
      url = removeDuplicateSubstring(
        JSON.parse(certificateModel.value.fileList[0].response).url,
        ':8111',
      )
    } else {
      url = removeDuplicateSubstring(certificateModel.value.fileList[0].response, ':8111')
    }
  }
  certificateForm.value.validate().then(async (data) => {
    if (data.valid) {
      if (certificateModel.value.id) {
        const res = await updateCertificateInfo({
          ...certificateModel.value,
          startTime: dayjs(certificateModel.value.startTime).format('YYYY-MM-DD'),
          endTime: dayjs(certificateModel.value.endTime).format('YYYY-MM-DD'),
          userId: userId.value,
          certificateFile: url,
        })
        if (res.data.code == 200) {
          uni.showToast({
            title: '修改成功',
            icon: 'success',
            duration: 2000,
          })
          certificateShow.value = false
          getUserInfo()
        }
      } else {
        const res = await addCertificateInfo({
          ...certificateModel.value,
          startTime: dayjs(certificateModel.value.startTime).format('YYYY-MM-DD'),
          endTime: dayjs(certificateModel.value.endTime).format('YYYY-MM-DD'),
          userId: userId.value,
          certificateFile: url,
        })
        if (res.data.code == 200) {
          uni.showToast({
            title: '新增成功',
            icon: 'success',
            duration: 2000,
          })
          certificateShow.value = false
          getUserInfo()
        }
      }
    }
  })
}

// 文件下载
const downloadFile = (file) => {
  console.log(file)

  uni.downloadFile({
    url: file, //仅为示例，并非真实的资源
    success: (res) => {
      if (res.statusCode === 200) {
        console.log('下载成功')
      }
    },
  })
}

// 删除工作经历
const delWork = async (item) => {
  uni.showModal({
    title: '提示',
    content: '确定删除吗？',
    confirmText: '确定',
    cancelText: '取消',
    success: async (res) => {
      if (res.confirm) {
        const res = await deleteWorkInfo(item.id)
        if (res.data.code == 200) {
          uni.showToast({
            title: '删除成功',
            icon: 'success',
            duration: 2000,
          })
          getUserInfo()
        }
      }
    },
  })
}

// 工作经历保存
const workSubmit = async () => {
  workForm.value.validate().then(async (data) => {
    if (data.valid) {
      if (workModel.value.id) {
        const res = await updateWorkInfo({
          ...workModel.value,
          startTime: dayjs(workModel.value.startTime).format('YYYY-MM-DD'),
          endTime: dayjs(workModel.value.endTime).format('YYYY-MM-DD'),
          userId: userId.value,
        })
        if (res.data.code == 200) {
          uni.showToast({
            title: '修改成功',
            icon: 'success',
            duration: 2000,
          })
          workShow.value = false
          getUserInfo()
        }
      } else {
        const res = await addWorkInfo({
          ...workModel.value,
          startTime: dayjs(workModel.value.startTime).format('YYYY-MM-DD'),
          endTime: dayjs(workModel.value.endTime).format('YYYY-MM-DD'),
          userId: userId.value,
        })
        if (res.data.code == 200) {
          uni.showToast({
            title: '新增成功',
            icon: 'success',
            duration: 2000,
          })
          workShow.value = false
          getUserInfo()
        }
      }
    }
  })
}

// 删除学历
const delSchool = async (item) => {
  uni.showModal({
    title: '提示',
    content: '确定删除吗？',
    confirmText: '确定',
    cancelText: '取消',
    success: async (res) => {
      if (res.confirm) {
        const res = await deleteSchoolInfo(item.id)
        if (res.data.code == 200) {
          uni.showToast({
            title: '删除成功',
            icon: 'success',
            duration: 2000,
          })
          getUserInfo()
        }
      }
    },
  })
}

// 籍贯选择事件
const columnChange = async ({ selectedItem, resolve, finish }) => {
  if (selectedItem.deep == 2) {
    finish()
  }
  const res = await getCityDict({
    id: selectedItem.value,
  })
  const data = res.data.data.map((item) => {
    return {
      label: item.name,
      value: item.id,
      deep: item.deep,
      children: [],
    }
  })
  if (data && data.length) {
    resolve(data)
  }
  // finish()
  // console.log('searchForm.company', searchForm.value)
}

// 户籍地址选择事件
const columnChange2 = async ({ selectedItem, resolve, finish }) => {
  const res = await getCityDict({
    id: selectedItem.value,
  })
  const data = res.data.data.map((item) => {
    return {
      label: item.name,
      value: item.id,
      deep: item.deep,
      children: [],
    }
  })
  if (data && data.length) {
    resolve(data)
  } else {
    finish()
  }
}

// 获取用户详细信息
const getUserInfo = async () => {
  const res = await getUserInfoDetail(userId.value)
  model.value = {
    ...res.data.data,
    nativePlaceList: [],
    residenceList: [],
  }
  userSchoolList.value = model.value.userSchoolList
  workList.value = model.value.userEmployedCompanyList
  certificateList.value = model.value.userCertificatesList
  contractList.value = model.value.userEmploymentContractsList
  familyList.value = model.value.userRelationshipList
  if (model.value.sex || model.value.sex == 0) {
    model.value.sex = model.value.sex + ''
  }
  if (model.value.deptId) {
    getDeptName(model.value.deptId, enabledDeptOptions.value)
    getPostList(model.value.deptId)
  }

  if (model.value.avatar) {
    fileList.value = [
      {
        url: model.value.avatar,
        response: model.value.avatar,
      },
    ]
  }
}

// 获取基地
const getBaseList = async () => {
  const res = await getBaseData()
  baseList.value = res.data.data.map((item) => {
    return {
      value: item.workPlace,
      label: item.workPlace,
    }
  })
}

// 获取厂区
const getFactoryList = async (workPlace) => {
  const res = await getFactoryData({
    workPlace,
  })
  factoryList.value = res.data.data.map((item) => {
    return {
      value: item.plantCode,
      label: item.plantName,
    }
  })
}

// 基地修改事件
const changeBase = async (data) => {
  getFactoryList(data.value)
  model.value.plantCode = ''
}

// 获取部门树
const getDeptTreeData = async () => {
  const res = await getDeptTree()
  enabledDeptOptions.value = filterDisabledDept(res.data.data)
}

// 根据id获取部门名称
const getDeptName = async (id, nodes) => {
  if (!Array.isArray(nodes)) return ''
  for (const node of nodes) {
    if (node.id === id) {
      model.value.deptName = node.label
    }
    if (node.children && node.children.length > 0) {
      getDeptName(id, node.children)
    }
  }
}

const showTreePicker = () => {
  return
  treePicker.value._show()
}

// 部门修改事件
const changeDept = (data, name) => {
  model.value.deptId = data[0]
  model.value.deptName = name
  model.value.postId = ''
  getPostList()
}

// 过滤禁用的部门
const filterDisabledDept = (deptList) => {
  return deptList.filter((dept) => {
    if (dept.disabled) {
      return false
    }
    if (dept.children && dept.children.length) {
      dept.children = filterDisabledDept(dept.children)
    } else {
      dept.children = []
    }
    return true
  })
}

// 获取岗位数据
const getPostList = async () => {
  const res = await getPostData({
    deptId: model.value.deptId,
  })
  postOptions.value = res.data.data.map((item) => {
    return {
      value: item.postId,
      label: item.postName,
    }
  })
}

// 获取城市字典
const getCityDictData = async () => {
  const res = await getCityDict({
    id: 0,
  })
  const data = res.data.data.map((item) => {
    return {
      label: item.name,
      value: item.id,
      deep: item.deep,
      children: [],
    }
  })
  console.log('datadata', data)

  companyList.value = [data] || []
}
</script>

<style lang="scss" scoped>
:deep() {
  .wd-upload__picture {
    border-radius: 50%;
  }
  .wd-card {
    box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.1);
  }
  .wd-select-picker__label {
    // margin-right: 0px;
  }
  .item-check {
    display: none;
  }
  .popTitle {
    position: absolute;
    left: 15px;
    top: 10px;
  }
  .wd-search {
    padding: 0 !important;
    width: 95vw;
  }
  .wd-input__inner {
    color: black !important;
  }
  .wd-table__header {
    z-index: 1 !important;
  }
  .cardBox {
    .wd-card__title-content {
      padding: 14upx 0upx;
    }
    .wd-card__footer {
      padding: 14upx 0upx;
    }
  }

  .is-light {
    background-color: white !important;
  }
  .wd-search__block {
    border: 1px solid #d4d3d3 !important;
  }
  .wd-picker__show {
    background-color: white;
  }
  .wd-picker__toolbar {
    background-color: white;
  }
}
.oppbox {
  :deep(.wd-popup) {
    background: transparent !important;
  }
}
.contentBox {
  background-color: white;
  border-radius: 16px;
}
.infoItem {
  display: flex;
  padding: 10px 15px;
  border-bottom: 1px solid #f5f5f5;
  .item-title {
    width: 100px;
    // 不换行
    white-space: nowrap;
    // 超出部分隐藏
    overflow: hidden;
    // 超出部分显示省略号
    text-overflow: ellipsis;
  }
}
.title {
  display: flex;
  justify-content: flex-end;
}
.border-t {
  border-top: 1px solid #f5f5f5;
}
.left-label {
  font-size: 27upx;
  color: #4f4f4f;
}
// 容器
.container {
  padding: 10px;
  height: 100vh;
  overflow-y: scroll;
  padding-bottom: 100px;
}
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.flexBox {
  display: flex;
  align-items: center;
  padding: 10px 15px;
}
// 底部按钮
.bottom-btn {
  position: fixed;
  bottom: 20px;
  left: 0;
  right: 0;
  padding: 10px;
  background-color: #fff;
  display: flex;
  justify-content: center;
  :deep() {
    .btn {
      width: 90%;
    }
  }
}
</style>
